//创建用户仓库
import {defineStore} from 'pinia'
import type {loginForm, responseData} from "@/api/user/type.ts";
import {reqLogin} from "@/api/user";
import {
    GET_TOKEN,
    GET_USERID,
    GET_USERNAME,
    REMOVE_ALL,
    SET_TOKEN,
    SET_USERID,
    SET_USERNAME
} from "@/utils/localStore.ts";

let useUserStore=defineStore('User',{
    //数据存储
    state:()=>{
        return{
            token:GET_TOKEN(),//获取token
            userId:GET_USERID(),//获取用户ID
            name:GET_USERNAME(),
        }
    },
    //逻辑功能
    actions: {
        //用户登录的方法
        async userLogin(data: loginForm) {
            let result: responseData = await reqLogin(data);
            //登陆成功 存储token
            if (result.code == 1) {
                //断言：当类型为string时存储}
                this.token = (result.msg as string);
                this.userId=(result.data.userId as string)
                this.name=(result.data.userName as string)
                //本地化持久存储 防止刷新后消失
                SET_TOKEN(result.msg as string);
                SET_USERID(result.data.userId as string);
                SET_USERNAME(result.data.userName as string);
                return 'ok';
            } else {
                return Promise.reject(new Error(result.msg))
            }
        },
        //用户退出
        userLogout(){
            this.token = ''
            REMOVE_ALL();
        }
    },
    getters:{

    }
})
//对外暴露获取仓库
export default useUserStore;